package com.mc.moring.main

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.BaseActivity
import com.mc.moring.base.HttpCallback
import com.mc.moring.base.SaveZiLiPageTool
import com.mc.moring.bean.AppVersionBean
import com.mc.moring.bean.GeoIpResult
import com.mc.moring.bean.ZiLiPageUserDataBean
import com.mc.moring.login.LoginActivity
import com.mc.moring.main.modle.MianModle
import com.mc.moring.main.modle.PermisosModle
import com.mc.moring.network.HttpResult
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.PointMgr
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.StringUtils
import com.mc.moring.widge.UpdateVersionDialog

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks

class SplashNewActivity : BaseActivity(), PermissionCallbacks {

    private var isShowVersion = true

    private var updateVersionDialog: UpdateVersionDialog? = null
    private lateinit var name:TextView
    private lateinit var solgen:TextView
    private lateinit var typefaceName:Typeface
    private lateinit var typefaceSlogen:Typeface

    override fun onCreate(savedInstanceState: Bundle?) {
        toNoTitleBar()
        super.onCreate(savedInstanceState)
        PointMgr.sendEvent("cl_app_plata")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_app_plata")
        setContentView(R.layout.activity_splash_new)
        name = findViewById(R.id.splash_name)
        solgen = findViewById(R.id.splash_slogan)
        setStyle()
        //使用startService方式启动service
        startService()
        val sharedPreferences = getSharedPreferences("firstTime", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString("firstTime", "false")
        editor.commit()
        init()
    }

    //使用startService方式启动service
    private fun startService() {
        val logcatIntent = Intent(this@SplashNewActivity, LogcatService::class.java)
        startService(logcatIntent)
    }

    private fun toNoTitleBar() {
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        requestWindowFeature(
            Window.FEATURE_NO_TITLE
        )
        window.setBackgroundDrawable(null)
    }

    private fun setStyle(){
        typefaceName = Typeface.createFromAsset(assets, "Poppins-Bold.ttf")
        name.typeface = typefaceName
        typefaceSlogen = Typeface.createFromAsset(assets, "Poppins-Regular.ttf")
        solgen.typeface = typefaceSlogen
    }

    override fun getActivity(): Activity {
        return this
    }

    override fun initView() {

        updateVersionDialog = UpdateVersionDialog(this)
        updateVersionDialog?.setDialogViewOnClickListener(object :
            UpdateVersionDialog.DialogViewOnClickListener {
            override fun onClickConfirm() {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data =
                    Uri.parse("market://details?id=${this@SplashNewActivity.packageName}")
                startActivity(intent)
            }
            override fun onClickCancel(isForce: Boolean) {
                if (isForce) {
                    finish()
                } else {
                    isShowVersion = false
                    skipNext()
                }


            }
        })

        val params: MutableMap<String, String> = java.util.HashMap()
        PermisosModle.instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                SharePreUtil.saveStringData("_getWebLinkConfig", data)
                LogUtils.logE("h5>$data")
            }

            override fun onFaill(e: String) {
                LogUtils.logE(e)
            }
        })
    }

    override fun initData() {
    }

    private fun skipNext() {
        lifecycleScope.launch(Dispatchers.Main){
            try {
                withTimeout(7000) {
                    if (isShowVersion) {
                        val map: MutableMap<String, String> = HashMap()
                        val targetVersion = getVersion()
                        map["version"] = targetVersion?:""
                        val result: HttpResult<String> = MianModle.instant.getVersion(map)
                        when(result) {
                             is HttpResult.Success -> {
                                 val data = result.value
                                 if (data.isNullOrEmpty()) {
                                   return@withTimeout
                                 }
                                 val (code, _, versionData) = Gson().fromJson(data, AppVersionBean::class.java)
                                 if (!versionData?.version.isNullOrEmpty()) {
                                     if (versionData?.version != targetVersion) {
                                         runOnUiThread {
                                             updateVersionDialog?.showToUpdateDialog(activity, versionData, true)
                                         }

                                         return@withTimeout
                                     }
                                 }

                            }
                            is HttpResult.Failure -> {
                                return@withTimeout
                            }
                        }
                    }
                    delay(3000)

                    val jsonString: String = SaveZiLiPageTool(this@SplashNewActivity).getKeyValue("user_info") ?: ""
                    LogUtils.logE("kelvin ---jsonString-===:$jsonString ")

                    if (!jsonString.isNullOrEmpty()) {
                        val userDataBean1: ZiLiPageUserDataBean =
                            GsonUtils.getGson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
                        ZiLiPageUserDataBean.setInstance(userDataBean1)
                        var userDataBean = ZiLiPageUserDataBean.getInstance()
                        if (userDataBean != null) {
                            if (!userDataBean.token.isNullOrEmpty()
                                && !userDataBean.customerId.isNullOrEmpty()) {
                                val intent = Intent(this@SplashNewActivity, MainActivity::class.java)
                                startActivity(intent)
                                finish()
                                return@withTimeout
                            }
                        }
                    }


                    if (requestCheckIP()) {
                        val intent = Intent(this@SplashNewActivity, LoginActivity::class.java)
                        startActivity(intent)
                        finish()
                        return@withTimeout
                    }

                    goIntoApp()
                }
            } catch (e: TimeoutCancellationException) {
                goIntoApp()
            }
        }
    }

    private fun goIntoApp() {
        val gotoPer = SharePreUtil.getStringData("DoNotShowAgain")
        if ( gotoPer.equals("TRUE") ){
            val intent = Intent(this@SplashNewActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        } else {
            val permisos = SaveZiLiPageTool(this@SplashNewActivity).getKeyValue("permisos")
            val perString = permisos + ""
            Log.e("----permisos",perString)
            if (!StringUtils.isEmpty(permisos)) {
                val privacy = SaveZiLiPageTool(this@SplashNewActivity).getKeyValue("privacy")
                val privaString = privacy + ""
                Log.e("----privacy",privaString)
                if (StringUtils.isEmpty(privacy)) {
                    val intent = Intent(this@SplashNewActivity, PrivacyActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    val intent = Intent(this@SplashNewActivity, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }
            } else {
                val intent = Intent(this@SplashNewActivity, PermisosActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

    }

    private suspend fun requestCheckIP(): Boolean {
        val map: MutableMap<String, String> = java.util.HashMap()
        val result: HttpResult<String> = MianModle.instant.getZiLiPageGeoIpResult(map)
        return when(result){
            is HttpResult.Success -> {
                val data = result.value
                if (!data.isNullOrEmpty()) {
                    val (code, _, geoIpData) = Gson().fromJson(data, GeoIpResult::class.java)
                    geoIpData?.countryIsoCode == "CL"
                } else {
                    false
                }

            }

            is HttpResult.Failure -> {
                false
            }
        }
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).build().show()
        }
    }

    fun getVersion(): String? {
        return try {
            val manager = packageManager
            val info = manager.getPackageInfo(packageName, 0)
            info.versionName
        } catch (e: Exception) {
            ""
        }
    }

    override fun onResume() {
        super.onResume()
        skipNext()

    }
}